import router from "./index.ts";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import {getLoginInfo, getToken} from "../utils/auth.ts";
import {useUserInfoStore} from "@/store/userInfo.ts";
import {initDynamicRouter, initUserRoleMenu} from "@/utils/RouterUtil.ts";
import {MenuOperationInfo, MenuTreeRes} from "@/interface/basicsInterface/systemManage";
import {basicsPage} from "@/model/PageModel.ts";

//全局进度条的配置
NProgress.configure({
    // easing: "ease", // 动画方式
    // speed: 1000, // 递增进度条的速度
    showSpinner: false, // 是否显示加载ico
    // trickleSpeed: 200, // 自动递增间隔
    // minimum: 0.3, // 初始化时的最小百分比
});
const whiteList = ["/login"]; // 没有重定向白名单

router.beforeEach(async (to, _) => {

    // 进度条开始
    NProgress.start();

    // window.document.title= to.meta.title
    if (typeof to.name === "string") {
        document.title = to.name;
    }

    // 判断用户是否已登录
    const hasToken = getToken();
    const userStore = useUserInfoStore()

    if (hasToken) {
        const lastRoutePath = localStorage.getItem('lastRoute');
        if (to.path === "/login") {
            // 如果已登录，则重定向到主页
            if (lastRoutePath && lastRoutePath !== to.path) {
                return (lastRoutePath);
            }
        }
        if (to.path !== "/login") {
            if (userStore.userInfos.init) {
                return true
            } else {
                // init为false,一定没有获取动态路由,就跳转到获取动态路由的方法
                const result: any = await userStore.getPagesInfo() //获取路由
                await initDynamicRouter(result.children[0].children, "basics")
                await initDynamicRouter(result.children[1].children, "control")
                const data: MenuOperationInfo[] = await userStore.getRoleMenuRelFun(JSON.parse(getLoginInfo()).roles[0].roleId)
                const controlPagesList: MenuTreeRes[] = initUserRoleMenu(data, result.children[1].children)
                const basicsPagesList: MenuTreeRes[] = initUserRoleMenu(data, result.children[0].children)
                controlPagesList.push(basicsPage)
                // 将基础组件的可操作菜单保存
                localStorage.setItem("basicsPagesList", JSON.stringify(basicsPagesList))
                localStorage.setItem("controlPagesList", JSON.stringify(controlPagesList))
                userStore.userInfos.init = true
                return {...to, replace: true}// hack方法 确保addRoute已完成
            }
        }
        return true
    }
    if (whiteList.indexOf(to.path) !== -1) {
        return true
    }
    NProgress.done();
    // 其他没有访问权限的页面被重定向到登录页面。
    return {path: `/login?redirect=${to.path}`}
});

router.afterEach((to, _) => {
    localStorage.setItem('lastRoute', to.path);
    // finish progress bar
    NProgress.done();
});
